using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Sustainalytics.Synchronization.Validation.Handlers.Common;

namespace Sustainalytics.Synchronization.Validation
{
    public class ValidationEngine
    {
        private readonly IEnumerable<IHandler> dataHandlers;

        private readonly InvalidCompaniesList companiesList = new InvalidCompaniesList();

        private readonly Log.Log log;

        public ValidationEngine(IEnumerable<IHandler> dataHandlers, Log.Log log)
        {
            this.dataHandlers = dataHandlers;
            this.log = log;
        }

        public async Task<InvalidCompaniesList> ValidateAsync()
        {
            var tasks =
                dataHandlers.Select(dataHandler => dataHandler.ForEachElementsAsync(
                    (validationResult) =>
                        {
                            if (!validationResult.IsValid)
                            {
                                log.AddMessages(validationResult.ValidationErrors);

                                companiesList.AddValidationFailures(validationResult.ValidationErrors);
                            }
                        })).ToList();

            await Task.WhenAll(tasks).ConfigureAwait(false);
            log.WriteLog();
            return companiesList;
        }
    }
}